package com.atguigu.gulimall.common.exception.global;

import com.atguigu.gulimall.common.exception.NameRepetitionException;
import com.atguigu.gulimall.common.exception.PurchaseReceiveException;
import com.atguigu.gulimall.common.utils.Constant;
import com.atguigu.gulimall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Luo Sheng
 * @school YiBin university
 * @create 2023-03-04 16:23
 */
/*@ControllerAdvice
@ResponseBody*/
@RestControllerAdvice(basePackages = "com.atguigu.gulimall")
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public R error(Exception e) {
        log.error("后端出现未知异常：{}",e.getMessage());
        if (e instanceof NameRepetitionException){
            log.error("后端出现异常：{}", ((NameRepetitionException) e).getMsg());
            return R.error(Constant.ServerException.NAME_REPETITION_ERROR.getCode(),
                    ((NameRepetitionException) e).getMsg());
        }else if (e instanceof MethodArgumentNotValidException){
            BindingResult bindingResult = ((MethodArgumentNotValidException) e).getBindingResult();
            // 将错误集合封装进入Map中
            Map<String,String> errorMap = new HashMap<>();
            bindingResult.getFieldErrors().forEach((item) -> {
                errorMap.put(item.getField(),item.getDefaultMessage());
            });
            return R.error(Constant.ServerException.PARAMETER_CHECK_ERROR.getCode(),
                    Constant.ServerException.PARAMETER_CHECK_ERROR.getMessage()).put("data",errorMap);
        }else if (e instanceof PurchaseReceiveException){
            return R.error(Constant.ServerException.PURCHASE_RECEIVE_ERROR.getCode(),
                    Constant.ServerException.PURCHASE_RECEIVE_ERROR.getMessage());
        }
        else{
            return R.error(Constant.ServerException.UNKNOWN_ERROR.getCode(),
                    Constant.ServerException.UNKNOWN_ERROR.getMessage()).put("data",e.getMessage());
        }
    }

}